/**
 * Created by tanbingqin on 2019/8/15.
 */
import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Alert, Popover, message, Button, Badge } from 'antd';
import EmailNotificationService from 'containers/setting/email-notification/email-notification.service'
import ResizeTable from "components/resize-table";
import errorMessage from 'share/errorMessage';
import SlideFrame from 'components/slide-frame'
import NewTemplate from 'containers/setting/email-notification/new-template'

class EmailTemplate extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      data: [],
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48},
        {title: messages('setting.key1186')/*业务描述*/, dataIndex: 'businessDescribe'},
        {
          title: messages('setting.key486'/*适用公司*/),
          dataIndex: 'customCompanyRelationResps',
          width: '20%',
          render: (value, record) => {
            return this.renderCompany(value, record)
          }
        },
        {
          title: messages('setting.key2160')/*适用表单*/,
          dataIndex: 'customFormRelationResps',
          width: '20%',
          render: (value, record) => {
            return this.renderForm(value, record)
          }
        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'valid',
          render: valid => (
            <Badge
              status={valid ? 'success' : 'error'}
              text={valid ? messages('common.status.enable') : messages('common.status.disable')}
            />
          )
        },
        {
          title: messages('setting.key2161')/*创建时间*/, dataIndex: 'createdDate', width: '20%',
          render: date => new Date(date).format('yyyy-MM-dd hh:mm')
        },
      ],
      pagination: {
        total: 0
      },
      templateVisible: false,
      slideParams: {}
    }
  }

  componentDidMount(){
    this.getList();
  }

  getList = () => {
    const { page, pageSize } = this.state;
    this.setState({loading: true});
    let param = {
      page,
      size: pageSize,
    };
    EmailNotificationService.getMailTemplate(param).then((response) => {
      response.data.map((item, index) => {
        item.key = item.id;
        item.index = index + page * pageSize + 1;
      });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          onChange: this.onChangePager,
          current: page + 1
        }
      })
    }).catch((e) => {
      errorMessage(e.response);
      this.setState({loading: false});
    });
  };

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, this.getList);
  };

  renderCompany = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      value.map((item, index) => {
        if (item.companyOID) {
          relationNameList.push(item.name);
        }
      });
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('setting.key1037'/*通用*/)}</span>
    }
  };

  renderForm = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      value.map((item, index) => {
        if (item.formOID) {
          relationNameList.push(item.formName);
        }
      });
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('setting.key1037'/*通用*/)}</span>
    }
  };

  showTemplate = () => {
    this.setState({
      templateVisible: true,
      slideParams: {
        templateVisible: true
      }
    });
  };

  editItem = (record) => {
    this.setState({
      templateVisible: true,
      slideParams: {
        templateVisible: true,
        record: record
      }
    });
  };

  handleCloseTemplate = (isSuccess) => {
    this.setState({
      templateVisible: false,
      slideParams: {
        templateVisible: false
      }
    }, () => {
      //根据是否是成功的返回，再决定是否刷新列表
      if (isSuccess) {
        this.getList();
      }
    });
  };

  handleOnClose = () => {
    this.setState({
      templateVisible: false,
      slideParams: {
        templateVisible: false
      }
    });
  };

  render() {
    const { pagination, columns, data, loading, templateVisible, slideParams } = this.state;
    const { tenantMode } = this.props;
    return (
      <div>
        <Alert
          message={messages('setting.key1908')/*注意*/}
          description={messages('setting.key2162')/*当重复分配时，系统发送邮件时将选取最新创建的消息模板*/}
          type="info"
          showIcon
        />
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total ? pagination.total : '0'})}
          </div>
          {/* 共total条数据 */}
          {tenantMode && (
            <div className="table-header-buttons">
              <Button type="primary" onClick={this.showTemplate}>
                {messages('common.create')}
              </Button>
            </div>
          )}
        </div>
        <ResizeTable
          columns={columns}
          onRow={(record) => {
            return {
              onClick: () => {this.editItem(record)}      // 点击行
            };
          }}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          size="middle"
        />

        <SlideFrame
          title={messages('setting.key1365')/*邮件通知*/}
          show={templateVisible}
          content={NewTemplate}
          afterClose={this.handleCloseTemplate}
          onClose={this.handleOnClose}
          params={slideParams}
        />
      </div>
    )
  }
}

EmailTemplate.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(EmailTemplate)
